package com.sheledon.flyCat.core.configuration.resolver;

import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sheledon
 */
public class YamlResolver implements Resolver{
    @Override
    public HashMap<String,Object> resolve(InputStream resource) {
        HashMap<String,Object> result = new HashMap<>();
        Yaml yaml = new Yaml();
        Object load = yaml.load(new InputStreamReader(resource));
        ((HashMap<String, Object>) load).forEach((k,v)->{
            if (v instanceof Map){
                asMap(v).forEach((k2,v2)->{
                    result.put(k+"."+k2, v2);
                });
            }else{
                result.put(k,v);
            }
        });
        return result;
    }
    private HashMap<String,Object> asMap(Object object){
        HashMap<String,Object> tmpMap = new HashMap<>();
        ((HashMap<String, Object>) object).forEach((k,v)->{
            if (v instanceof Map){
                HashMap<String,Object> map = asMap(v);
                map.forEach((k2,v2)->{
                    tmpMap.put(k+"."+k2,v2);
                });
            }else{
                tmpMap.put(k,v);
            }
        });
        return tmpMap;
    }

}
